var Rx = require("rxjs");
var operators = require("rxjs/operators");
var SERVER_CONST = require("../server-const");
var express = require("express");
var router = express.Router();
var model = require("../model/chatModel");
var user = model.user;
var post = model.post;
var channels = model.channels;
var teams = model.teams;
var channelMembers = model.channelMembers;
var teamMembers = model.teamMembers;
var util = require("../server-util/util");
var mongoose = require("mongoose");
var subject = require("../subject");
const { next } = require("../subject");
/* GET user listing. */
router.get("/", function (req, res, next) {
	res.send("respond with a resource");
});
/**
 * @api {GET} /user/login 登录
 * @apiSampleRequest off
 * @apiParam (params) {String} Username
 * @apiParam (params) {String} Password
 * @apiGroup user
 */

router.get("/login", function (req, res, next) {
	user
		.aggregate([
			{
				$match: {
					Username: req.query.Username,
					Password: req.query.Password,
				},
			},
			{
				$lookup: {
					from: "files",
					localField: "_id",
					foreignField: "UserId",
					as: "files",
				},
			},
			{
				$project: {
					data: "$$ROOT",
					avatar: {
						$filter: {
							input: "$files",
							as: "files",
							cond: {
								$eq: ["$$files.PostFileType", "avatar"],
							},
						},
					},
				},
			},
		])
		.exec((fError, fResult) => {
			
			if (fError) {
				
				util.res.error({
					res,
					msg: "账号或者密码错误",
				});
			} else {
				
				if (!fResult || fResult.length < 1) {
					
					util.res.error({
						res,
						msg: "账号或者密码错误",
					});
				} else {
					
					let avatar = fResult[0].avatar[0] ? fResult[0].avatar[0] : null;
					delete fResult[0].data.files;
					let result = {
						...fResult[0].data,
						avatar,
					};
					util.res.success({
						res,
						data: result,
					});
				}
			}
		});
});
/**
 * @api {POST} /user/register 注册
 * @apiSampleRequest off
 * @apiParam (params) {String} register
 * @apiParam (params) {String} Email
 * @apiParam (params) {String} Password
 * @apiParam (params) {String} checkPassword
 * @apiParam (params) {String} Username
 * @apiParam (params) {String} PhoneNumberPrefix
 * @apiParam (params) {String} PhoneNumber
 * @apiParam (params) {String} Agree
 * @apiGroup user
 */
router.post("/register", function (req, res, next) {
	new Rx.Observable((ob) => {
		//查找是否有Email相同的数据
		user.find(
			{
				Email: req.body.Email,
			},
			function (fError, fResult) {
				//数据库报错
				if (!!fError) {
					ob.error({
						msg: fError,
					});
				} else {
					//有重复数
					if (fResult.length > 0) {
						ob.error({
							msg: "账号存在",
						});
					}
					//没有重复数据
					else {
						new user(
							Object.assign(
								{
									Email: null,
									Password: null,
									Username: null,
									Prefix: null,
									Phone: null,
									Agreement: null,
									CreateAt: null,
									UpdateAt: null,
									DeleteAt: null,
									AuthData: null,
									AuthService: null,
									EmailVerified: null,
									Nickname: null,
									FirstName: null,
									LastName: null,
									Position: null,
									Roles: null,
									AllowMarketing: null,
									Props: null,
									NotifyProps: null,
									LastPasswordUpdate: null,
									LastPictureUpdate: null,
									FailedAttempts: null,
									Locale: null,
									MfaActive: null,
									MfaSecret: null,
								},
								{
									...req.body,
									CreateAt: new Date().getTime(),
								}
							)
						).save(function (error, result) {
							//数据库报错
							if (!!error) {
								ob.error({
									msg: error,
								});
							}
							//存入成功
							else {
								ob.next(result._doc);
								ob.complete();
							}
						});
					}
				}
			}
		);
	})
		.pipe(
			operators.concatMap((userinfo) => {
				return new Rx.Observable((ob) => {
					channels.find(
						{
							DisplayName: SERVER_CONST.DEFAULT_CHANNEL,
						},
						function (fError, fResult) {
							if (fResult.length > 0) {
								new channelMembers({
									ChannelId: fResult[0]._doc._id,
									UserId: userinfo._id,
									Roles: null,
									LastViewedAt: null,
									MsgCount: 0,
									MentionCount: 0, //注意这里是自增字段,要给他赋予初始值为0,不能是null,如果为null,无法自增.
									NotifyProps: null,
									LastUpdateAt: null,
									SchemeUser: null,
									SchemeAdmin: null,
								}).save(function (error, result) {
									var obj = Object.assign({}, userinfo, {
										defaultChannel: result._doc,
									});
									ob.next(obj);
									ob.complete();
								});
							}
						}
					);
				});
			}),
			operators.concatMap((userinfo) => {
				return new Rx.Observable((ob) => {
					teams.find(
						{
							DisplayName: SERVER_CONST.DEFAULT_TEAM,
						},
						function (fError, fResult) {
							if (fResult.length > 0) {
								new teamMembers({
									TeamId: fResult[0]._doc._id,
									UserId: userinfo._id,
									Roles: null,
									DeleteAt: null,
									SchemeUser: null,
									SchemeAdmin: null,
								}).save(function (error, result) {
									var obj = Object.assign({}, userinfo, {
										defaultTeam: result._doc,
									});
									ob.next(obj);
									ob.complete();
								});
							}
						}
					);
				});
			}),
			operators.catchError((err) => {
				util.res.error({
					res,
					msg: err.msg,
				});
				return Rx.empty();
			})
		)
		.subscribe((result) => {
			util.res.success({
				res,
				data: result,
			});
		});
});

/**
 * @api {POST} /user/getUserInfoByUserId 获取用户信息，通过UserId
 * @apiSampleRequest off
 * @apiParam (params) {String} UserId
 * @apiGroup user
 */
router.post("/getUserInfoByUserId", function (req, res, next) {
	let UserId = mongoose.Types.ObjectId(req.body.UserId);
	util.getUserInfo(UserId).exec(function (fError, fResult) {
		if (!!fError) {
			util.res.error({
				res,
				msg: "找不到这个人",
			});
		} else {
			if (fResult.length > 0) {
				var result = Object.assign(
					{},
					{
						name: fResult[0].Username,
						userid: fResult[0]._id,
					},
					fResult[0]
				);
				util.res.success({
					res,
					data: result,
				});
			} else {
				util.res.error({
					res,
					msg: "找不到这个人",
				});
			}
		}
	});
});
/**
 * @api {POST} /user/accessFromToken 通过token登陆
 * @apiSampleRequest off
 * @apiParam (params) {String} token
 * @apiGroup user
 */
router.post("/accessFromToken", function (req, res, next) {
	let UserId = mongoose.Types.ObjectId(req.body.token);
	util.getUserInfo(UserId).exec(function (fError, fResult) {
		//数据库报错
		if (!!fError) {
			util.res.error({
				res,
				msg: "token失效",
			});
		} else {
			if (fResult.length > 0) {
				var result = Object.assign(
					{},
					{
						name: fResult[0].Username,
						userid: fResult[0]._id,
					},
					fResult[0]
				);
				util.res.success({
					res,
					data: result,
				});
			} else {
				util.res.error({
					res,
					msg: "token失效",
				});
			}
		}
	});
});

/**
 * @api {POST} /user/fetchNotices 获取通知
 * @apiSampleRequest off
 * @apiParam (params) {String} token
 * @apiGroup user
 */

router.post("/fetchNotices", util.checkAuth, function (req, res, next) {
	util.res.success({
		res,
		data: [
			{
				id: "000000001",
				avatar:
					"https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png",
				title: "你收到了 14 份新周报",
				datetime: "2017-08-09",
				type: "notification",
			},
			{
				id: "000000002",
				avatar:
					"https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png",
				title: "你推荐的 曲妮妮 已通过第三轮面试",
				datetime: "2017-08-08",
				type: "notification",
			},
			{
				id: "000000003",
				avatar:
					"https://gw.alipayobjects.com/zos/rmsportal/kISTdvpyTAhtGxpovNWd.png",
				title: "这种模板可以区分多种通知类型",
				datetime: "2017-08-07",
				read: true,
				type: "notification",
			},
			{
				id: "000000004",
				avatar:
					"https://gw.alipayobjects.com/zos/rmsportal/GvqBnKhFgObvnSGkDsje.png",
				title: "左侧图标用于区分不同的类型",
				datetime: "2017-08-07",
				type: "notification",
			},
			{
				id: "000000005",
				avatar:
					"https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png",
				title: "内容不要超过两行字，超出时自动截断",
				datetime: "2017-08-07",
				type: "notification",
			},
			{
				id: "000000006",
				avatar:
					"https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg",
				title: "曲丽丽 评论了你",
				description: "描述信息描述信息描述信息",
				datetime: "2017-08-07",
				type: "message",
				clickClose: true,
			},
			{
				id: "000000007",
				avatar:
					"https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg",
				title: "朱偏右 回复了你",
				description: "这种模板用于提醒谁与你发生了互动，左侧放『谁』的头像",
				datetime: "2017-08-07",
				type: "message",
				clickClose: true,
			},
			{
				id: "000000008",
				avatar:
					"https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg",
				title: "标题",
				description: "这种模板用于提醒谁与你发生了互动，左侧放『谁』的头像",
				datetime: "2017-08-07",
				type: "message",
				clickClose: true,
			},
			{
				id: "000000009",
				title: "任务名称",
				description: "任务需要在 2017-01-12 20:00 前启动",
				extra: "未开始",
				status: "todo",
				type: "event",
			},
			{
				id: "000000010",
				title: "第三方紧急代码变更",
				description:
					"冠霖提交于 2017-01-06，需在 2017-01-07 前完成代码变更任务",
				extra: "马上到期",
				status: "urgent",
				type: "event",
			},
			{
				id: "000000011",
				title: "信息安全考试",
				description: "指派竹尔于 2017-01-09 前完成更新并发布",
				extra: "已耗时 8 天",
				status: "doing",
				type: "event",
			},
			{
				id: "000000012",
				title: "ABCD 版本发布",
				description:
					"冠霖提交于 2017-01-06，需在 2017-01-07 前完成代码变更任务",
				extra: "进行中",
				status: "processing",
				type: "event",
			},
		],
	});
});

module.exports = router;
